<template>
  <view>
    <u-modal :show-cancel-button="true" v-model="show" @confirm="confirm" @cancel="show = false" :content="content"></u-modal>
    <view v-if="isShow" class="class-btn">
      <view class="tip">您还未加入任何班级</view>
      <view class="btn">
        <u-button @click="joinClass" type="primary">加入班级</u-button>
      </view>
    </view>
    <view v-else-if="isCreate" class="class-btn">
      <view class="tip">您还未创建任何班级</view>
      <view class="btn">
        <u-button @click="createClazz" type="success">创建班级</u-button>
      </view>
    </view>
    <view v-else>
      <view class="cl">
        <view class="class-name">{{ clazz.name }}班</view>
        <view class="class-info" v-if="isAudit">
          <u-button size="mini" @click="clazzInfo" type="primary">班级信息</u-button>
        </view>
        <view class="class-info" v-if="!isAudit">
          <u-button size="mini" @click="exitClazz" type="primary">退出班级</u-button>
        </view>
      </view>
      <u-line color="blue" />
      <view class="navbar">
        <u-grid :col="4">
          <u-grid-item @tap="member">
            <u-icon name="account" :size="46"></u-icon>
            <view class="grid-text">成员</view>
          </u-grid-item>
          <u-grid-item @tap="apply">
            <u-icon name="list-dot" :size="46"></u-icon>
            <view class="grid-text">请销假</view>
          </u-grid-item>
          <u-grid-item @tap="discuss">
            <u-icon name="chat" :size="46"></u-icon>
            <view class="grid-text">讨论区</view>
          </u-grid-item>
          <u-grid-item @tap="group">
            <u-icon name="grid" :size="46"></u-icon>
            <view class="grid-text">分组</view>
          </u-grid-item>
        </u-grid>
      </view>
      <u-line color="blue" />
      <view class="tap">
        <text class="title">班级日志</text>
      </view>
      <u-line color="blue" />
      <view class="time-line">
        <u-time-line>
          <view class="time-line-item">
            <u-time-line-item v-for="(data,index) in dataFiles" :key="index" nodeTop="2">
              <template v-slot:node>
                <view class="u-node">
                  <!-- 此处为uView的icon组件 -->
                  <u-icon v-if="data.type === 1" name="word" color="#2979ff" custom-prefix="custom-icon" :size="50"/>
                  <u-icon v-if="data.type === 2" name="PPT" color="#2979ff" custom-prefix="custom-icon" :size="50"/>
                  <u-icon v-if="data.type === 3" name="excel" color="#2979ff" custom-prefix="custom-icon" :size="50"/>
                  <u-icon v-if="data.type === 4" name="PDF" color="#2979ff" custom-prefix="custom-icon" :size="50"/>
                </view>
              </template>
              <template v-slot:content>
                <view>
                  <view class="time-line-time">
                    <text class="time">{{ data.gmtCreate | dateTimeFormatter }}</text>
                  </view>
                  <view class="time-line-title" @click="dataFileClick(data)">{{ data.name }}</view>
                </view>
              </template>
            </u-time-line-item>
          </view>
        </u-time-line>
      </view>
      <u-loadmore :status="status" />
      <u-action-sheet :list="list1" @click="click1" v-model="show2"></u-action-sheet>
      <u-popup v-model="show1" mode="top">
        <view class="popup">
          <view class="title">文件保存路径</view>
          <br>
          <view class="word-break">
            {{ tip }}
          </view>
        </view>
      </u-popup>
      <view class="bottom-btn" v-if="isAudit">
        <u-button @click="toPostData" type="primary" :ripple="true" size="medium">发布资料</u-button>
      </view>
    </view>
  </view>
</template>

<script>
import {getUserInfo, removeUserInfo, setUserInfo} from "../../common/auth";
import download from "../../utils/downloader";
import {timestampFormat} from "../../utils/date";

export default {
  data() {
    return {
      list1:[{text: '在线预览'},{text: '下载'},{text: '收藏'}],
      show1: false,
      tip: '',
      dataFiles: [],
      currentDataFile: {},
      page: 1,
      status: '',
      show2: false,

      isShow: false,
      isCreate: false,
      clazz: {},
      //是否是审核者
      isAudit:false,
      // 模态框
      show: false,
      content: '您确定要退出班级吗？'
    };
  },
  onLoad(){
    uni.$emit("setVuexUserInfo",{user:null,isLoginPage: false});
    let isCreate = this.$store.getters.role === '教师';
    // 教师拥有创建班级的权限
    if (isCreate){
      this.$u.api.getClazzByUserId(this.$store.getters.id).then(res => {
        if (res.data){
          // 该教师已创建过课程
          this.clazz = res.data;
          this.isAudit = true;
          this.initial();
        }else {
          this.isCreate = isCreate;
        }
      })
    }else {
      // 从redis中获取该用户的班级，如果从本地获取会不准确（班主任踢出一个学生，无法修改学生的本地缓存）
      this.$u.api.getInfo().then(res => {
        let user = res.data;
        if (this.$store.getters.clazzId !== user.clazzId) {
          removeUserInfo();
          setUserInfo(user);
          this.$store.commit("SET_CLAZZ_ID",user.clazzId)
        }
        if (user.clazzId !== '0'){
          this.$u.api.getClazzById(user.clazzId).then(res => {
            this.clazz = res.data;
            this.initial();
          })
        }else {
          this.isShow = true;
        }
      })
    }
  },
  methods: {
    initial(){
      this.page = 1;
      this.total = 0;
      this.getDataFiles().then(res => {
        this.dataFiles = res.data;
        this.total = res.total;
        uni.stopPullDownRefresh();
      })
    },
    async getDataFiles(){
      return await this.$u.api.getDataFilePage(this.clazz.id,this.page);
    },
    dataFileClick(data){
      this.currentDataFile = data;
      this.show2 = true;
    },
    click1(index){
      if (index === 0){
        this.toFileShow(this.currentDataFile);
      }else if (index === 1){
        download.load(this.currentDataFile.path,this.currentDataFile.name,false).then(([err,res]) => {
          if (err != null){
            this.$u.toast("出错啦，错误信息：" + err)
          }else {
            // #ifndef H5
            this.tip = res.savedFilePath;
            this.show1 = true;
            // #endif
            console.log(res)
          }
        })
      }else {
        let data = {
          userId: this.$store.getters.id,
          dataFileId: this.currentDataFile.id
        }
        this.$u.api.saveCollect(data).then(res => {
          if (res.code === 200){
            this.$u.toast("收藏成功！");
          }
        })
      }
    },
    toFileShow(dataFile){
      let index = dataFile.path.lastIndexOf(".");
      let data = {
        name: dataFile.name,
        path: dataFile.path.substr(0,index)
      }
      uni.setStorage({
        key: 'pdf-url',
        data: JSON.stringify(data),
        success: (res) => {
          this.$u.route({
            url: 'pages/show_pdf/show_pdf'
          });
        },
        fail: (err) => {
          console.log(err)
          this.$u.toast("出错啦！");
        }
      })

    },
    toPostData(){
      this.$u.route({
        url: 'pages/post_data/post_data',
        params: {
          id: this.clazz.id
        }
      });
    },
    clazzInfo(){
      this.$u.route({
        url: '/pages/clazz_info/clazz_info',
        params: {
          id: this.clazz.id
        }
      })
    },
    joinClass() {
      this.$u.route('/pages/join_clazz/join_clazz')
    },
    createClazz() {
      this.$u.route('/pages/create_clazz/create_clazz')
    },
    apply() {
      if (this.isAudit) {
        this.$u.route({
          url:'pages/audit_ask_for_leave/audit_ask_for_leave',
          params: {
            id: this.clazz.id
          }
        });
      }else {
        this.$u.route('pages/apply/apply');
      }
    },
    discuss() {
      this.$u.route({
        url: '/pages/discuss/discuss',
        params: {
          name: this.clazz.name + '班',
          id: 'clazz:' + this.clazz.id
        }
      })
    },
    group(){
      this.$u.route('pages/group/group');
    },
    member(){
      this.$u.route({
        url: 'pages/member/member',
        params: {
          id: this.clazz.id,
          flag: true
        }
      });
    },
    exitClazz(){
      this.show = true;
    },
    confirm(){
      this.$u.api.exitClazz(this.$store.getters.id, this.clazz.id).then(res => {
        if (res.code === 200) {
          let user = getUserInfo();
          removeUserInfo();
          user.clazzId = '0';
          setUserInfo(user)
          this.$store.commit("SET_CLAZZ_ID",'0')
          this.$u.route({
            type: 'tab',
            url: '/pages/mine/mine'
          })
        }
      })
    }
  },
  filters: {
    dateTimeFormatter:timestampFormat
  }
}
</script>

<style lang="scss">
.class-btn{
  text-align: center;
  margin: 50rpx 40rpx;
  .tip{
    color: #e37470;
    font-weight: bolder;
  }
  .btn{
    margin-top: 20rpx;
  }
}
.cl{
  display: flex;
  justify-content: space-between;
  align-items: center;
  .class-name {
    font-size: 35rpx;
    margin: 40rpx 0 30rpx 45rpx;
    color: black;
    font-weight: bolder;
  }
  .class-info{
    margin-right: 20rpx;
  }
}

.grid-text {
  font-size: 28rpx;
  margin-top: 4rpx;
  color: $u-type-info;
}
.tap {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .title {
    margin: 40rpx 0 30rpx 45rpx;
    color: black;
    font-weight: bolder;
    font-size: 35rpx;
  }

}
.time-line {

  // #ifdef APP-PLUS || MP
  margin: 40rpx 0 100rpx 45rpx;
  // #endif
  // #ifdef H5
  margin: 40rpx 0 0 45rpx;
  padding-bottom: 70rpx;
  // #endif
  .time-line-item {
    .time-line-time {
      display: flex;
      justify-content: space-between;
      width: 400rpx;
      color: black;
      font-size: 28rpx;
      font-weight: bolder;
      margin-bottom: 30rpx;

    }

    .time-line-title {
      width: 650rpx;
      height: 50rpx;
      background-color: #FEF0F0;
      line-height: 50rpx;
      padding-left: 20rpx;
      color: #2979ff;
      font-size: 28rpx;
    }
  }
}
.bottom-btn{
  font-size: 30rpx;
  font-weight: bolder;
  bottom: 0;
  right: 50%;
  left: 32%;
  position: fixed;
  margin-bottom: 20rpx;
}
.popup{
  font-size: 40rpx;
  margin: 30rpx;
  .title {
    text-align: center;
    color: #2B85E4;
    margin-bottom: 20rpx;
  }
  .word-break{
    word-wrap: break-word;
  }
}
</style>
